<template>
	<div class="foSi14 poRel" style="padding: 20px;">
		<div class="borRad20 coFFF hei34 dis disAl cuPo poAbs fanhui bac6b7" @click.stop="fanhui()">返回</div>
		<div style="height: 30px;"></div>
		<div class="mar" style="width: 840px;">
			<div class="foSi12 titl">付费约课</div>
			<el-form ref="ruleForm2" :model="ruleForm2" :rules="rules2">
				<div class="hei44 dis disAl item-l mar-bott10" style="padding: 0 15px;">
					<div class="label">付费约课</div>
					<div class="dis disAl">
						<div class="dis disAl cuPo" @click.stop="ruleForm2.paid = 1">
							<div class="dis disAl disJuC bacFFF borRad50"
								style="width: 14px;height: 14px;border: 1px solid #6b7cdd;">
								<div v-if="ruleForm2.paid === 1" class="borRad50"
									style="width: 6px;height: 6px;background: #6b7cdd;"></div>
							</div>
							<div class="mar-left5">开启</div>
						</div>
						<div class="dis disAl cuPo mar-left30" @click.stop="ruleForm2.paid = 0">
							<div class="dis disAl disJuC bacFFF borRad50"
								style="width: 14px;height: 14px;border: 1px solid #6b7cdd;">
								<div v-if="ruleForm2.paid === 0" class="borRad50"
									style="width: 6px;height: 6px;background: #6b7cdd;"></div>
							</div>
							<div class="mar-left5">关闭</div>
						</div>
					</div>
				</div>
				<div v-if="ruleForm2.paid === 1" class="hei44 dis disAl item-l mar-bott10" style="padding: 0 15px;">
					<div class="label"><span class="mar-right5" style="color: #FF0000;">*</span>原价（元/次）</div>
					<el-form-item prop="originalPrice" class="mp0">
						<el-input v-model="ruleForm2.originalPrice" style="width: 140px;" placeholder="请输入原价" />
					</el-form-item>
				</div>
				<div v-if="ruleForm2.paid === 1" class="hei44 dis disAl item-l" style="padding: 0 15px;">
					<div class="label">优惠价（元/次）</div>
					<el-input v-model="ruleForm2.discounts" style="width: 140px;" placeholder="请输入优惠价" />
					<span class="mar-left10">课程实际售价</span>
				</div>
				<div class="foSi12 titl mar-top30">会员卡约课</div>
				<div class="dis item-l" style="padding: 10px 15px;">
					<div class="label"><span class="mar-right5" style="color: #FF0000;">*</span>支持卡类型</div>
					<div style="width: 650px;">
						<el-checkbox v-model="ruleForm2.dateCardAll" @change="handleCheckAllChange">期限卡</el-checkbox>
						<div style="height: 10px;"></div>
						<div class="mar-bott20" style="padding-left: 20px;">
							<el-checkbox-group v-model="ruleForm2.dateCard" @change="handleCheckedCitiesChange">
								<el-checkbox v-for="(item,index) in dateCardList" class="mar-bott10"
									style="margin-right: 40px;" :label="item.id"
									:key="index">{{item.name}}</el-checkbox>
							</el-checkbox-group>
						</div>
						<el-checkbox v-model="ruleForm2.cardTimeAll" @change="handleCheckAllChange1">次数卡</el-checkbox>
						<div style="height: 10px;"></div>
						<div style="padding-left: 20px;">
							<el-checkbox-group v-model="ruleForm2.cardTime" @change="handleCheckedCitiesChange1">
								<el-checkbox v-for="(item,index) in cardTimeList" class="mar-bott10"
									style="margin-right: 40px;" :label="item.id" :key="index">
									<div class="dis disAl">
										<span class="mar-right10">{{item.name}} 每节课收费</span>
										<el-form-item :prop="`${item.id}`" :rules="rules2.value" class="mp0">
											<el-input v-model="item.nums" style="width: 140px;" placeholder="请输入次数" />
										</el-form-item>
										<span class="mar-left10">次</span>
									</div>
								</el-checkbox>
							</el-checkbox-group>
						</div>
            <el-checkbox v-model="ruleForm2.cardStoredAll" @change="handleCheckAllChange2">储值卡</el-checkbox>
            <div style="height: 10px;"></div>
            <div style="padding-left: 20px;">
              <el-checkbox-group v-model="ruleForm2.cardStored" @change="handleCheckedCitiesChange2">
                <el-checkbox v-for="(item,index) in cardStoredList" class="mar-bott10"
                             style="margin-right: 40px;" :label="item.id" :key="index">
                  <div class="dis disAl">
                    <span class="mar-right10">{{item.name}} 每节课收费</span>
                    <el-form-item :prop="`${item.id}`" :rules="rules3.value" class="mp0">
                      <el-input v-model="item.nums" style="width: 140px;" placeholder="请输入金额" />
                    </el-form-item>
                    <span class="mar-left10">元</span>
                  </div>
                </el-checkbox>
              </el-checkbox-group>
            </div>
					</div>
				</div>
			</el-form>
		</div>

		<div class="dis disAl disJuC " style="padding: 30px 0;">
			<div class="dis disAl hei34 borRad20 coFFF cuPo bac6b7" style="padding: 0 24px;"
				@click.stop="submitForm('ruleForm2')">保存</div>
			<div class="mar-left30 dis disAl hei34 borRad20 coFFF cuPo" style="background: #616b74;padding: 0 24px;"
				@click.stop="fanhui()">取消</div>
		</div>
	</div>
</template>

<script>
	import {
		getXuan
	} from '@/utils/limits.js'
	import {
		mapGetters
	} from 'vuex'
	import {
		courseDetails,
		courseAddEdit
	} from '@/api/coures'
	import {
		schedCardList
	} from '@/api/member'
	export default {
		name: 'courseEdit3',
		components: {},
		data() {
			const validatePrice = (rule, value, callback) => {
				var reg = new RegExp('^-?[0-9]*.?[0-9]*$')
				if (this.ruleForm2.paid === 1) {
					if (!reg.test(value) || !value || value < 0.01) {
						callback(new Error('请输入不小于0的数值，最多两位小数'))
					} else {
						callback()
					}
				} else {
					callback()
				}
			}
			const validateValue = (rule, value, callback) => {
				var reg = new RegExp('^-?[0-9]*.?[0-9]*$')
				var pd = false
				this.ruleForm2.cardTime.forEach(item => {
					if (Number(item) === Number(rule.field)) {
						pd = true
					}
				})
				if (pd) {
					this.cardTimeList.forEach(item => {
						if (Number(item.id) === Number(rule.field)) {
							value = item.nums
						}
					})
					if (!reg.test(value) || !value || value < 0.1) {
						callback(new Error('请输入次数(最多一位小数)'))
					} else {
						callback()
					}
				} else {
					callback()
				}
			}
			return {
				dateCardList: [],
				cardList: [],
        cardStoredList1: [],
        cardStoredList: [],
				cardTimeList1: [],
				cardTimeList: [],
				ruleForm2: {
					paid: 1,
					originalPrice: null,
					discounts: null,
					dateCard: [],
					dateCardAll: true,
					cardTime: [],
					cardTimeAll: true,
					cardStored: [],
          cardStoredAll: true,
					frequency: [],
				},
				rules2: {
					originalPrice: [{
						required: true,
						trigger: 'blur',
						validator: validatePrice
					}],
					value: [{
						required: true,
						trigger: 'blur',
						validator: validateValue
					}],
				},
				rules3: {
					originalPrice: [{
						required: true,
						trigger: 'blur',
						validator: validatePrice
					}],
					value: [{
						required: true,
						trigger: 'blur',
						validator: validateValue
					}],
				},
				type: '',
				cid: '',
				url: ''
			}
		},
		computed: {
			...mapGetters([
				'permission_routes',
				'roles'
			])
		},
		created() {
			var query = this.$route.query
			this.type = Number(query.type)
			this.cid = query.cid
			this.url = '/course/courseParticulars?type=' + query.type + '&cid=' + query.cid
			var xuanList = [{
				name: '编辑课程',
				url: '/course/courseEdit3?type=' + query.type + '&cid=' + query.cid,
				pd: true
			}]
			var xuanList1 = getXuan(xuanList, this.roles)
			this.$store.dispatch('user/changeXuan', {
				key: 'xuanList',
				value: xuanList1
			})
			this.$store.dispatch('user/changeXuan', {
				key: 'xuan',
				value: 0
			})
			this.getMember()
		},
		methods: {
			getMember() {
				schedCardList({
					'keyword': ''
				}).then(response => {
					const {
						data
					} = response
					this.dateCardList = data.term
					this.cardTimeList = data.numtime
					this.cardStoredList = data.stored
					this.dateCardList.forEach(item => {
						this.cardList.push(item.id)
					})
					this.cardTimeList.forEach(item => {
						this.cardTimeList1.push(item.id)
					})
					this.cardStoredList.forEach(item => {
						this.cardStoredList1.push(item.id)
					})
					this.getList()
				}).catch(error => {
					console.log(error)
				})
			},
			fanhui() {
				this.$router.go(-1)
			},
			handleCheckAllChange2(val) {
				this.ruleForm2.cardStored = val ? this.cardStoredList1 : [];
			},
			handleCheckAllChange1(val) {
				this.ruleForm2.cardTime = val ? this.cardTimeList1 : [];
			},
			handleCheckedCitiesChange2(value) {
				let checkedCount = value.length;
				this.ruleForm2.cardStoredAll = checkedCount === this.cardStoredList.length;
			},
			handleCheckedCitiesChange1(value) {
				let checkedCount = value.length;
				this.ruleForm2.cardTimeAll = checkedCount === this.cardTimeList.length;
			},
			handleCheckAllChange(val) {
				this.ruleForm2.dateCard = val ? this.cardList : [];
			},
			handleCheckedCitiesChange(value) {
				let checkedCount = value.length;
				this.ruleForm2.dateCardAll = checkedCount === this.dateCardList.length;
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
            const supportId = this.ruleForm2.dateCard.join(',');
            // const supportIdArr = this.ruleForm2.dateCard.join(',');
            const weixuan = [];
            const frequency = [];
            this.cardTimeList.forEach(item => {
							if (this.ruleForm2.cardTime.indexOf(item.id) !== -1) {
								frequency.push({
									id: item.id,
									name: item.name,
									nums: item.nums
								})
							}else{
                weixuan.push({
                  id:item.id
                })
              }
						})
            const storeds = [];
            this.cardStoredList.forEach(item => {
							if (this.ruleForm2.cardStored.indexOf(item.id) !== -1) {
                storeds.push({
									id: item.id,
									name: item.name,
									nums: item.nums
								})
                // supportIdArr.push(
                //   item.id
                // )
							}else{
                weixuan.push({
                  id:item.id
                })
              }
						})
            this.dateCardList.forEach(item => {
              if (this.ruleForm2.dateCard.indexOf(item.id) === -1) {
                weixuan.push({
                  id:item.id
                })
              }
            })
						courseAddEdit({
							'id': this.cid,
							'paid_course': this.ruleForm2.paid,
							'orig_price': this.ruleForm2.originalPrice,
							'sell_price': this.ruleForm2.discounts,
							'support_id': supportId,
							'numtime': JSON.stringify(frequency),
							'storeds': JSON.stringify(storeds),
              'type': this.type,
              'weixuan':JSON.stringify(weixuan)
						}).then(response => {
							this.fanhui()
						}).catch(error => {
							console.log(error)
						})
					} else {
						this.$message.error('请按规则填写完整信息')
						return false
					}
				})
			},
			getList() {
				courseDetails({
					'courseid': this.cid // 1团课2精品课3私教课4班课
				}).then(response => {
					const {
						data
					} = response
					this.ruleForm2 = {
						paid: data.paid_course,
						originalPrice: data.orig_price,
						discounts: data.sell_price,
						dateCard: data.support_id.split(',').map(Number),
						dateCardAll: true,
						cardTime: [],
						cardTimeAll: true,
						cardStored: [],
						cardStoredAll: true,
					}
					this.ruleForm2.dateCardAll = this.ruleForm2.dateCard.length === this.dateCardList.length;
					var frequency = data.numtime ? JSON.parse(data.numtime) : []
					var storeds = data.storeds ? JSON.parse(data.storeds) : []
					var ids = []
          frequency.forEach(item => {
            ids.push(item.id)
          })
					this.cardTimeList.forEach((item, index) => {
						if (ids.indexOf(item.id) !== -1) {
							this.cardTimeList[index].nums = frequency[ids.indexOf(item.id)].nums
						}
					})
					this.ruleForm2.cardTime = ids
					this.ruleForm2.cardTimeAll = ids.length === this.cardTimeList.length;

					var ids2 = []
          storeds.forEach(item => {
            ids2.push(item.id)
          })
					this.cardStoredList.forEach((item, index) => {
						if (ids2.indexOf(item.id) !== -1) {
							this.cardStoredList[index].nums = storeds[ids2.indexOf(item.id)].nums
						}
					})
					this.ruleForm2.cardStored = ids2
					this.ruleForm2.cardStoredAll = ids2.length === this.cardStoredList.length;
					console.log(this.ruleForm2.dateCard)
					console.log(this.ruleForm2.cardTime)
					console.log(this.ruleForm2.cardStored)
				}).catch(error => {
					console.log(error)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.fanhui {
		background: #6b7cdd;
		padding: 0 24px;
		right: 63px;
		top: 10px;
		z-index: 10;
	}

	.titl {
		height: 25px;
		color: #787878;
	}

	.label {
		float: left;
		width: 135px;
		min-height: 32px;
		line-height: 32px;
		padding-right: 10px;
		white-space: nowrap;
	}

	.item-l {
		background: #f2f2f2;
	}

	.item-r {
		width: 420px;
		padding: 0 15px;
	}

	::v-deep .el-upload:focus {
		color: #000 !important;
	}

	::v-deep .el-upload-list {
		display: none;
	}

	::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
		background-color: #6b7cdd;
		border-color: #6b7cdd;
	}

	::v-deep .el-checkbox__input.is-focus .el-checkbox__inner {
		border-color: #6b7cdd;
	}

	::v-deep .el-checkbox__label {
		color: #000 !important;
	}
</style>
